<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/reqFlow' }">我的申请</el-breadcrumb-item>
        <el-breadcrumb-item>立项申请</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 立项申请 -->
        <div class="card-title">立项申请</div>
        <el-form label-width="100px" :model="editForm" prop="day" :disabled="showDatas">

          <el-form-item label="项目经理">
            <el-input :disabled="isReview" v-model="editForm.pmp"></el-input>
          </el-form-item>

          <el-divider></el-divider>
           <el-form-item label="审批意见"  v-if="isReview">
          <el-input type="textarea" :rows="3" placeholder="审批意见(20字以内)" v-model="editForm.note"></el-input>

          </el-form-item>
          <el-form-item label="优先级">
            <el-radio-group v-model="editForm.flowPriority">
              <el-radio label="0">普通</el-radio>
              <el-radio label="1">重要</el-radio>
              <el-radio label="2">紧急</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="消息推送">
            <el-checkbox-group v-model="editForm.msgPush">
              <el-checkbox label="1">站内消息通知</el-checkbox>
              <el-checkbox label="2">企业微信通知</el-checkbox>
              <el-checkbox label="3">邮件通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

        </el-form>
        <div class="card-line">
          <!-- 立即申请 -->
          <el-button type="primary" size="small" @click="onSubmit" :disabled="isSubmit" v-if="isSetUp">立即申请</el-button>
          <!-- 重置 初始化表单数据 -->
          <el-button size="small" @click="save" :disabled="isSubmit" v-if="isSetUp">暂存草稿</el-button>
            <!-- 修改编辑 -->
          <el-button type="primary"  size="small" @click="edit" :disabled="isSubmit" v-if="isEditForm">修改编辑</el-button>
             <!-- 重置 初始化表单数据 -->
          <el-button type="success" size="small" @click="agreed" :disabled="isSubmit" v-if="isReview">通过</el-button>
            <!-- 修改编辑 -->
          <el-button type="warning"  size="small" @click="refused" :disabled="isSubmit" v-if="isReview">驳回</el-button>
          <!-- 返回 -->
          <el-button class="clean-both" size="small" style="float:right" @click="goBack">返回</el-button>
          <div class="clean-both"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 查看表单数据
      showDatas: false,
      // 是否申请
      isSetUp: true,
      // 是否修改
      isEditForm: false,

      // 是否审查
      isReview: false,

      isSubmit: false,
      editForm: {
        pmp: '',
        flowPriority: '',
        msgPush: []
      },
      users: []
    };
  },
  methods: {

    // 拒绝申请
    refused: function () {
      let row = this.$route.query.datas;

      // 初始数据源
      let list = JSON.parse(row.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = list.nodes[0].id;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      let params = {
        // 工单编号
        flowCode: row.flowCode,
        // 发起人
        flowOriginator: row.flowOriginator,
        // 当前审批节点
        flowCurrentNode: setUpNodeId,
        // 当前审批人
        flowCurrentUser: row.flowOriginator,
        // 工单状态
        status: 5,
        // 处理结果
        result: row.flowCurrentNode + ', 申请被驳回！',
        // 工单优先级
        flowPriority: this.editForm.flowOriginator,
        // 消息推送
        msgPush: this.editForm.msgPush.toString(),
        // 审批历史-审批节点
        flowNode: row.flowCurrentNode,
        // 审批历史-审批意见
        note: this.editForm.note,
        // 审批历史-审批结果
        workResult: 3
      };

      this.$http.raw('api/updateOrderStatus', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '审批成功，已驳回申请！',
            type: 'success'
          });
          this.goBack();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 通过申请
    agreed: function () {
      let row = this.$route.query.datas;

      // 初始数据源
      let list = JSON.parse(row.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = row.flowCurrentNode;
      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      let end = '';

      for (let i = 0; i < list.nodes.length; i++) {
        if (nextNode.length === 1) {
          if (nextNode[0] === list.nodes[i].id) {
            end = list.nodes[i].type;
          }
        }
      }
      if (end === '结束') {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          // 发起人
          flowOriginator: row.flowOriginator,
          // 当前审批节点
          flowCurrentNode: nextNode.toString(),
          // 当前审批人
          flowCurrentUser: '',
          // 工单状态
          status: 4,
          // 处理结果
          result: setUpNodeId + ', 审批已通过并结束！',
          // 工单优先级
          flowPriority: '',
          // 消息推送
          msgPush: '',
          // 审批历史-审批节点
          flowNode: setUpNodeId,
          // 审批历史-审批意见
          note: this.editForm.note,
          // 审批历史-审批结果
          workResult: 2
        };

        this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            this.$message({
              message: '审批成功，已批准通过！',
              type: 'success'
            });
            this.goBack();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      } else {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          // 发起人
          flowOriginator: row.flowOriginator,
          // 当前审批节点
          flowCurrentNode: nextNode.toString(),
          // 当前审批人
          flowCurrentUser: users[0].toString(),
          // 工单状态
          status: 3,
          // 处理结果
          result: setUpNodeId + ', 审批已通过！',
          // 工单优先级
          flowPriority: this.editForm.flowOriginator,
          // 消息推送
          msgPush: this.editForm.msgPush.toString(),
          // 审批历史-审批节点
          flowNode: setUpNodeId,
          // 审批历史-审批意见
          note: this.editForm.note,
          // 审批历史-审批结果
          workResult: 2
        };

        this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            this.$message({
              message: '审批成功，已批准通过！',
              type: 'success'
            });
            this.goBack();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }
    },

    // 获取所有节点
    getNode () {
      // 初始数据源
      let nodeDB = this.$route.query.datas;
      // 当前节点ID
      let node = this.$route.query.node;

      if (node === 1) {
        this.isSetUp = false;
        this.isEditForm = true;
        let formDatas = JSON.parse(nodeDB.formJson);

        this.editForm.pmp = formDatas.pmp;
        this.editForm.flowPriority = nodeDB.flowPriority === null ? '' : nodeDB.flowPriority.toString();
        this.editForm.msgPush = nodeDB.msgPush.split(',');
      }
      if (node === 2) {
        this.isSetUp = false;
        this.showDatas = true;
        let formDatas = JSON.parse(nodeDB.formJson);

        this.editForm.pmp = formDatas.pmp;
        this.editForm.flowPriority = nodeDB.flowPriority === null ? '' : nodeDB.flowPriority.toString();
        this.editForm.msgPush = nodeDB.msgPush.split(',');
      }
      if (node === 3) {
        this.isSetUp = false;
        this.isEditForm = false;
        this.isReview = true;
        let formDatas = JSON.parse(nodeDB.formJson);

        this.editForm.pmp = formDatas.pmp;
        this.editForm.flowPriority = nodeDB.flowPriority === null ? '' : nodeDB.flowPriority.toString();
        this.editForm.msgPush = nodeDB.msgPush.split(',');
      }
    },
    // 提交
    onSubmit () {
      // 初始数据源
      let nodeDB = this.$route.query.datas;

      let list = JSON.parse(nodeDB.flowJson);

      // 获取发起人
      let flowUser = this.$store.state.userinfo.userId;
      let nodes = list.nodes;

      // 获取发起节点的ID
      let setUpNodeId = '';
      // 判断发起人是否在审批节点中
      for (let i = 0; i < nodes.length; i++) {
        for (let j = 0; j < nodes[i].users.length; j++) {
          if (nodes[i].users[j] === flowUser) {
            setUpNodeId = nodes[i].id;
          } else {
            if (nodes[i].type === '开始') {
              setUpNodeId = nodes[i].id;
            }
          }
        }
      }

      // 根据发起节点ID查找下一步审批节点的审批人、审批节点ID
      let users = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          list.nodes.map(key => {
            if (item.target === key.id) {
              users.push(key.users);
            }
          });
        }
      });
      // 根据发起节点ID查找下一步审批节点ID
      let nextNode = [];
      list.edges.map(item => {
        if (setUpNodeId === item.source) {
          nextNode.push(item.target);
        }
      });

      for (let m = 0; m < nodes.length; m++) {
        if (nextNode.length === 1) {
          if (nextNode[0] === nodes[m].id) {
            if (nodes[m].type !== '结束') {
              let formItem = {
                pmp: this.editForm.pmp
              };
              let params = {
                tblWorkOrder: {
                  // 关联流程ID
                  flowId: nodeDB.flowId,
                  // 流程JSON
                  flowJson: nodeDB.flowJson,
                  // 表单JSON
                  formJson: JSON.stringify(formItem),
                  // 工单当前处理节点
                  flowCurrentNode: nextNode.toString(),
                  // 工单当前处理人ID
                  flowCurrentUser: users[0].toString(),
                  // 工单优先级
                  flowPriority: this.editForm.flowPriority,
                  // 流程工单发起人
                  flowOriginator: this.$store.state.userinfo.userId,
                  // 流程工单发起时间
                  flowOriginatorTime: new Date(),
                  // 工单状态
                  status: 2,
                  // 工单处理结果
                  result: '已发起',
                  // 消息推送
                  msgPush: this.editForm.msgPush.toString()
                },
                tblWorkResult: {
                  flowNode: setUpNodeId,
                  note: '发起申请',
                  result: 1
                }
              };

              this.$http.raw('api/insertWorkOrder', params).then(res => {
                let { code } = res;
                // 判断Code状态
                if (code === 0) {
                  this.$message({
                    message: '发起流程成功！',
                    type: 'success'
                  });
                  this.goBack();
                }
              }).catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            } else {
              let formItem = {
                pmp: this.editForm.pmp
              };
              let params = {
                tblWorkOrder: {
                  // 关联流程ID
                  flowId: nodeDB.flowId,
                  // 流程JSON
                  flowJson: nodeDB.flowJson,
                  // 表单JSON
                  formJson: JSON.stringify(formItem),
                  // 工单当前处理节点
                  flowCurrentNode: nextNode.toString(),
                  // 工单当前处理人ID
                  flowCurrentUser: '',
                  // 工单优先级
                  flowPriority: this.editForm.flowPriority,
                  // 流程工单发起人
                  flowOriginator: this.$store.state.userinfo.userId,
                  // 流程工单发起时间
                  flowOriginatorTime: new Date(),
                  // 工单状态
                  status: 4,
                  // 工单处理结果
                  result: '已发起并通过审批！',
                  // 消息推送
                  msgPush: this.editForm.msgPush.toString()
                },
                tblWorkResult: {
                  flowNode: setUpNodeId,
                  note: '发起申请并通过审批！',
                  result: 2
                }
              };

              this.$http.raw('api/insertWorkOrder', params).then(res => {
                let { code } = res;
                // 判断Code状态
                if (code === 0) {
                  this.$message({
                    message: '发起流程成功！',
                    type: 'success'
                  });
                  this.goBack();
                }
              }).catch(err => {
                if (err === undefined) {
                  this.$message({
                    message: '服务器响应异常！',
                    type: 'error'
                  });
                  return false;
                }
              });
            }
          }
        }
      }
    },
    // 数据暂存操作
    save () {
      // 初始数据源
      let nodeDB = this.$route.query.datas;

      let list = JSON.parse(nodeDB.flowJson);

      // 获取发起节点的ID
      let setUpNodeId = list.nodes[0].id;
      let formItem = {
        pmp: this.editForm.pmp
      };
      let params = {
        tblWorkOrder: {
          // 关联流程ID
          flowId: nodeDB.flowId,
          // 流程JSON
          flowJson: nodeDB.flowJson,
          // 表单JSON
          formJson: JSON.stringify(formItem),
          // 工单处理记录ID  审批记录表
          // workOrderRecord: '',
          // 工单当前处理节点
          flowCurrentNode: setUpNodeId,
          // 工单当前处理人ID
          flowCurrentUser: this.$store.state.userinfo.userId,
          // 工单优先级
          flowPriority: this.editForm.flowPriority,
          // 流程工单发起人
          flowOriginator: '',
          // 流程工单发起时间
          flowOriginatorTime: '',
          // 工单状态
          status: 1,
          // 工单处理结果
          result: '暂存草稿',
          // 消息推送
          msgPush: this.editForm.msgPush.toString()
        }
      };

      this.$http.raw('api/insertWorkOrder', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '已保存草稿！',
            type: 'success'
          });
          this.goBack();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 修改表单数据
    edit () {
      let row = this.$route.query.datas;
      let formItem = {
        pmp: this.editForm.pmp
      };
      let params = {
        flowCode: row.flowCode,
        // 表单JSON
        formJson: JSON.stringify(formItem),
        // 工单优先级
        flowPriority: this.editForm.flowPriority,
        // 消息推送
        msgPush: this.editForm.msgPush.toString()
      };

      this.$http.post('api/updateWorkOrder', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$message({
            message: '已保存修改！',
            type: 'success'
          });
          this.goBack();
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 获取所有用户
    getUsers () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 返回上一步
    goBack () {
      this.$router.go(-1);
    }
  },
  created () {
    // 获取所有用户
    this.getUsers();

    // 获取节点数据
    this.getNode();
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
